<template>
    <view>
        <view class="list">
            <view class="item" v-for="(item,index) of list" :key="index">
                <easy-cacheimage :image-src="item.image" :cache="cache" :cacheTime="0.002"></easy-cacheimage>
                <text>{{item.content}}</text>
            </view>
        </view>
        <view><h2 @click="clearSavedFiles">clearAll</h2><h2 @click="Info">Info</h2></view>
    </view>
</template>
<script>
    const MockData = require('@/static/easy-cacheimage/mock-data.json')
    import easyCacheimage from '@/components/easy-cacheimage/easy-cacheimage.vue'
    export default{
        components:{
            easyCacheimage
        },
        data(){
            return {
                list:MockData.slice(0,1),//建议逐张图片调试方便观察打印信息
                cache:true,//动态缓存调试
            }
        },
        methods:{
            clearCachedImage(){
                // 清除全部缓存图片saveFile
                try {
                    const storage = uni.getStorageInfoSync();
                    const cachedKeys = storage.keys.filter(key => key.includes('cached-image'))
                    cachedKeys.forEach(key=>{
                        const cachedUrl = uni.getStorageSync(key);
                        uni.removeStorageSync(key);
                        uni.removeSavedFile({filePath:cachedUrl}).then(res=>{
                            console.log("res: " + JSON.stringify(res));
                        })
                    })
                } catch (err) {
                    console.log("err: " + JSON.stringify(err));
                }
            },
            async clearSavedFiles(){
                // 清除所有saveFile
                const res = await uni.getSavedFileList()
                const fileList = res[1]&&res[1].fileList;
                if(!fileList.length){
                    uni.showToast({title:'无图片缓存可清',icon:'none'})
                    return
                }
                fileList.forEach((file,index)=>{
                    uni.removeSavedFile({filePath:file.filePath}).then(res=>{
                        console.log("res: " + JSON.stringify(res));
                        if(index == fileList.length-1){
                            uni.showToast({title:'已清除全部图片缓存',icon:'none'})
                        }
                    })
                })
            },
            Info(){
                // 调试查看缓存信息
                const res = uni.getStorageInfoSync();
                console.log("res: " + JSON.stringify(res));
                uni.getSavedFileList().then(res=>{
                    console.log("res: " + JSON.stringify(res));
                })
            }
        },
        onLoad() {
        }
    }
</script>
<style scoped>
    .list{display: flex;justify-content: space-between;flex-wrap: wrap;padding: 32rpx;background: #F1F1F1;}
    .list .item{width: 48%;background: #fff;margin-bottom: 80rpx;border-radius: 20rpx;}
    .list .item image{
        width: 100%;
        height: 500rpx;
    }
</style>